<script setup lang='ts'>
import { useOrgAddOrUpdate, useOrgShow, useOrgLabelList } from '@fl/api/xf-api'
import { SearchForm } from '@fl/components'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import searchMap from '../components/search-map.vue'
import type { orgSaveParam } from '@fl/api/xf-api/model/industry-evaluation-model'
import { formatTime } from '@fl/utils'
import FlUpload from '@fl/components/fl-upload.vue'

const { go } = useRouter()
const form = ref()

const route = useRoute()
const _id = route.params?.id as string
const id = ref(_id ?? '')
const _parkId = route.query?.parkId as string
const parkId = ref(_parkId ?? '')
const _areaId = route.query?.areaId as string
const areaId = ref<string>(_areaId ?? '')
const _isReadOnly = route.query?.isReadOnly as string
const isReadOnly = ref<string>(_isReadOnly ?? '')
const labelOptions = ref<any>()
const updateKey = ref<number>(1)
// console.log('id', id.value, '-', parkId.value, '-', areaId.value)

const initialState = {
    address: '',
    enterpriseLabelIdList: [],
    enterpriseCode: '',
    enterpriseName: '',
    legalPerson: '',
    establishTime: '',
    registeredCapital: undefined,
    logoImage: '',
    registeredAddress: '',
    beListedFlag: '1',
    marketValue: undefined,
    revenueValue: undefined,
    enterpriseType: '',
    latitude: 0,
    longitude: 0,
}
const state = ref<orgSaveParam>(cloneDeep(initialState))

// 项目详情
const { data, isLoading } = useOrgShow(id)
watchEffect(() => {
    if (data.value) {
        state.value = {
            ...data.value,
            enterpriseLabelIdList: data.value.enterpriseLabelList.reduce((pre, cur) => {
                pre.push(cur.id)
                return pre
            }, []),
            address: data.value.registeredAddress
        }
        updateKey.value = +new Date()
        console.log('state.value', state.value)
    }
})

// 标签列表
const { data: labelList } = useOrgLabelList()
watchEffect(() => {
    if (labelList.value) {
        labelOptions.value = cloneDeep(labelList.value.records).reduce((pre, cur) => {
            cur.value = cur.id
            cur.label = cur.lableName
            pre.push(cur)
            return pre
        }, [])
        console.log('labelOptions', labelOptions.value)
    }
})

// 图片上传
function urlChange() {
    form.value.formInstance.formInstance.clearValidate('logoImage');
}


// 提交表单
const { isPending, mutate } = useOrgAddOrUpdate()

async function submit() {
    const valid = await form.value.formInstance.formInstance.validate()
    if (valid) {
        const stateObj = toRaw(state.value)
        const params = {
            ...stateObj,
            registeredAddress: state.value.address,
            establishTime: formatTime(state.value.establishTime, 'yyyy-MM-dd HH:mm:ss'),
            parkId: parkId.value,
            areaId: areaId.value,
        }

        console.log('params', params)

        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                goBack()
            },
        })
    }
}

function goBack() {
    id.value = ''
    go(-1)
}

const columns = computed(() => {
    return [
        {
            fieldProps: {
                maxlength: 18,
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '统一信用代码',
            prop: 'enterpriseCode',
        },
        {
            fieldProps: {
                maxlength: 20,
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '公司名称',
            prop: 'enterpriseName',
        },
        {
            fieldProps: {
                maxlength: 10,
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '法定代表人',
            prop: 'legalPerson',
        },
        {
            fieldProps: {
                type: 'datetime',
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '成立日期',
            prop: 'establishTime',
            valueType: 'date-picker'
        },
        {
            fieldProps: {
                maxlength: 7,
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '注册资本',
            prop: 'registeredCapital',
            fieldSlots: {
                append: () => '万元'
            }
        },
        {
            colProps: {
                span: 16,
            },
            label: '注册地址',
            prop: 'address',
        },
        {
            colProps: {
                span: 8,
            },
            label: '企业LOGO',
            prop: 'logoImage',
        },
        {
            colProps: {
                span: 8,
            },
            fieldProps: {
                disabled: true,
            },
            label: '经度',
            prop: 'longitude',
        },
        {
            colProps: {
                span: 8,
            },
            fieldProps: {
                disabled: true,
            },
            label: '纬度',
            prop: 'latitude',
        },
        {
            colProps: {
                span: 8,
            },
            prop: 'none', // 占位用
            hasLabel: false
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '上市企业',
            prop: 'beListedFlag',
            valueType: 'radio',
            options: [
                {
                    label: '是',
                    value: '1'
                },
                {
                    label: '否',
                    value: '0'
                },
            ]
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '市值（亿）',
            prop: 'marketValue',
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '营收（亿）',
            prop: 'revenueValue',
        },
        {
            fieldProps: {
                filterable: true,
                multiple: true,
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '企业标签',
            prop: 'enterpriseLabelIdList',
            valueType: 'select',
            options: computed(() => {
                return labelOptions.value
            })
        },
        {
            fieldProps: {
                disabled: computed(() => !!isReadOnly.value),
            },
            label: '行业类别',
            prop: 'enterpriseType',
        },
    ]
})

const rules = {
    enterpriseCode: [
        {
            message: '统一信用代码',
            required: true,
        },
    ],
    enterpriseName: [
        {
            message: '公司名称',
            required: true,
        },
    ],
    legalPerson: [
        {
            message: '法定代表人',
            required: true,
        },
    ],
    establishTime: [
        {
            message: '成立日期',
            required: true,
        },
    ],
    registeredCapital: [
        {
            message: '注册资本',
            required: true,
        },
    ],
    logoImage: [
        {
            message: '企业LOGO',
            required: true,
        },
    ],
    registeredAddress: [
        {
            message: '注册地址',
            required: true,
        },
    ],
    marketValue: [
        {
            message: '市值',
            required: true,
        },
    ],
    revenueValue: [
        {
            message: '营收',
            required: true,
        },
    ],
    address: [
        {
            message: '注册地址',
            required: true,
        },
    ],
    longitude: [
        {
            message: '经度',
            required: true,
        },
    ],
    latitude: [
        {
            message: '纬度',
            required: true,
        },
    ],
    enterpriseType: [
        {
            message: '行业类别',
            required: true,
        },
    ],
}

</script>

<template>
    <ElCard shadow="never">
        <el-button @click="goBack">
            返回企业列表
        </el-button>

        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="mt-20">
                <SearchForm ref="form" v-model="state" :columns="columns" :rules="rules" :label-width="120" submit-text="搜索" :has-footer="false" labelPosition="top">
                    <template #plus-field-address>
                        <searchMap v-model:state="state"  v-model:readonly="isReadOnly"></searchMap>
                    </template>

                    <template #plus-field-logoImage>
                        <el-image style="width:120px;height:120px;" v-if="isReadOnly" :src="state.logoImage" :preview-src-list="[state.logoImage]" fit="contain"></el-image>
                        <div v-else>
                            <FlUpload :key="updateKey"
                                  v-model="state.logoImage"
                                  @success="urlChange"
                            />
                        </div>
                        
                    </template>

                    <template #plus-field-none>
                        <div></div>
                    </template>

                </SearchForm>
            </div>

            <div class="mx-auto mt20 flex justify-center" v-if="!isReadOnly">
                <el-button @click="goBack">
                    取消
                </el-button>

                <SubmitBtn type="primary" @click="submit" :loading="isPending">
                    提交
                </SubmitBtn>
            </div>
        </template>
    </ElCard>
</template>
